<!DOCTYPE html>
<html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <title></title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        html, body, #map{
            height: 100%;
            width: 100%;
        }
        #marklayer_layer image:not(#carMarkerImage){
            width: 36px !important;
            height: 36px !important;
            transform: translate(-5px,-30px);
        }
        image#carMarkerImage {
            width: 32px;
            height: 64px;
        }
    </style>
    <script>
        var host="http://10.3.102.90";
        var itemName="/Portal"
        var map_wkid = "3857";

        window.urlPath = host;
        document.write('<script src="'+host+itemName+'/api/apiframe/js/base_host_config.js"><\/script>');
        document.write('<script src="'+host+itemName+'/arcgis2D.js"><\/script>');
        document.write('<script src="'+host+itemName+'/js/jquery/jquery-1.9.1.min.js"><\/script>');
    </script>
</head>
<body>
<div id="map"></div>
</body>
<script type="text/javascript">
    //arcgis 对象
    var MapObj,TianDiTuLayerObj,ExtentObj,RAddMarkObj,SimpleLineSymbolObj
    ,GraphicObj,ColorObj,PolylineObj,TokenUtilObj,RMapUtilObj,WebMercatorUtilsObj;

    //arcgis map属性数据
    var newData = {};

    //图层显示相关对象
    var map,graphic,rmark,graphicsLayerObj;

    //图层数据
    var paths=[],pointList=[];

    //轨迹回放相关,初始x,初始y,结束x,结束y,动画,计数,是否动画
    var startPointX,startPointY,endPointX,endPointY,moving,count=0,isMoving=false;

    require([
        "esri/map",
        "rgis/layers/TianDiTuLayer",
        "esri/geometry/Extent",
        "rgis/tools/RAddMark",
        "esri/symbols/SimpleLineSymbol",
        "esri/graphic",
        "esri/Color",
        "esri/geometry/Polyline",
        "rgis/tools/TokenUtil",
        "rgis/tools/RMapUtil",
        "esri/geometry/webMercatorUtils",
        "dojo/domReady!"
    ], function (Map,TianDiTuLayer,Extent,RAddMark,SimpleLineSymbol,Graphic,Color,Polyline,TokenUtil,RMapUtil,webMercatorUtils) {
        MapObj = Map;
        TianDiTuLayerObj = TianDiTuLayer;
        ExtentObj = Extent;
        RAddMarkObj = RAddMark;
        SimpleLineSymbolObj = SimpleLineSymbol;
        GraphicObj = Graphic;
        ColorObj = Color;
        PolylineObj = Polyline;
        TokenUtilObj = TokenUtil;
        RMapUtilObj = RMapUtil;
        WebMercatorUtilsObj = webMercatorUtils;

        createMapLayer();
    });
    function createMapLayer(){
        map = new MapObj("map", {
            logo: false,
            zoom: 10,
            minZoom: 3,
            maxZoom:15,
            sliderPosition: "bottom-right",
            sliderStyle: "small",
            extent: new ExtentObj({
                xmax: 12996436.020995652,
                xmin: 12915565.483327374,
                ymax: 4871956.410904499,
                ymin: 4836260.2473023385,
                spatialReference: {wkid: baseData.map_wkid}
            })
        });
        //创建图层数组
        var layerArr = {
            "title": "电子地图应用模板",
            "subTitle": "",
            "style": "",
            "map": {
                "logo": false,
                "basemaps": [{
                    "id": "basemap_vec",
                    "type": "wmtsTDT",
                    "group": "矢量地图",
                    "visible": true,
                    "icon": "",
                    "layers": [{
                        "id": "vec",
                        "label": "天地图矢量地图",
                        "type": "wmtsTDT",
                        "visible": true,
                        "opacity": 1,
                        "displayLevels": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
                        "style": "default",
                        "identifier": "vec",
                        "tileMatrixSet": "w",
                        "wkid":3857,
                        "format": "tiles",
                        "url":baseData.layer_vec
                    },{
                        "id": "vec_c",
                        "label": "天地图矢量地图注记",
                        "type": "wmtsTDT",
                        "visible": true,
                        "opacity": 1,
                        "displayLevels": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
                        "style": "default",
                        "identifier": "cva",
                        "tileMatrixSet": "w",
                        "format": "tiles",
                        "wkid":3857,
                        "url": baseData.layer_vecZj
                    }]
                }]
            },
            "version": "1.0.0",
            "copyRight": "中国铁道科学研究院电子计算技术研究所."
        }

        var rMapUtil= new RMapUtilObj()
        var tokenUtil = new TokenUtilObj(null,baseData.tokenhost+"/Portal/*.action");

        tokenUtil.getToken('mn9ieCApH8A08UR9V8shlYd9Dac3RRTGei+aLVCyaLVTVC51VUmcLrvgcBRARuCY',function(rep){
            if(!rep.token||!!rep.error){alert(rep.error);return;}
            userKey = rep.token;
            layerArr.map.basemaps.forEach(function (item,i) {
                if(i>=0){
                    $.each(item.layers, function(index, input){
                        var layer = rMapUtil.createSingleLayer(input,rep.token);
                        map.addLayer(layer, item.layers.length+i);
                    });
                }
            })
        });

        rmark = new RAddMarkObj();
        map.addLayer(rmark);
    }

    //创建坐标点的路线
    function addMarkerAndRoute(){
        var geometry = new PolylineObj({
            type:'polyline',
            paths:paths,
            spatialReference:3857,
        })
        var symbol = new SimpleLineSymbolObj(SimpleLineSymbolObj.STYLE_SOLID, new ColorObj([255, 0, 0]), 8);
        graphic=new GraphicObj();
        graphic.geometry=geometry;
        graphic.symbol=symbol;
        map.graphics.add(graphic);

        addEndMarker();
        addStartMarker();
        // centerPointAndZoom();

        //调整图层,将Marker图层放到线路图层之上
        document.getElementById('map_gc').appendChild(document.getElementById('marklayer_layer'));
    }

    //起点
    function addStartMarker(){
        rmark.addMarker({
            x: startPointX,
            y: startPointY,
            id: 'pointAddStart',
            img: "/static/startRoute.png",
        });
    }

    //终点
    function addEndMarker(){
        rmark.addMarker({
            x: endPointX,
            y: endPointY,
            id: 'pointAddEnd',
            img: "/static/endRoute.png",
        });
    }

    //车
    function addCarMarker(x,y){
        rmark.addMarker({
            x: x,
            y: y,
            id: 'pointCarIcon',
            img: "/static/carIcon.png",
        });
    }

    //车辆轨迹
    function drawRoute(data){
        if(isMoving){
            return;
        }

        pointList=[];
        paths=[];

        rmark.clear();
        map.graphics.clear();

        pointList=data;
        initData();
    }

    //车辆定位
    function drawCarLocation(data){
        if(isMoving){
            return;
        }
        rmark.clear();
        map.graphics.clear();

        let lnglat = changePosXy(data.lng,data.lat);

        let x = lnglat[0];
        let y = lnglat[1];

        map.setZoom(map.getMaxZoom());

        setTimeout(() => {
            addCarMarker(x,y);
            setCarMarkerStyle();
        }, 1000)
    }

    function initData(data){
        //去除重复坐标
        let arr = [];

        for (let i = 0; i < this.pointList.length; i++) {
            if(i===0){
                arr.push(this.pointList[i]);
                continue;
            }
            let obj = arr.find((item) => {
                return item.lat===this.pointList[i].lat && item.lng===this.pointList[i].lng;
            })
            if(!obj){
                arr.push(this.pointList[i]);
            }
        }
        this.pointList = arr;

        //封装轨迹坐标
        let pathArr = [];
        for (let i = 0; i < pointList.length; i++) {
            let path = [];

            let lnglat = changePosXy(pointList[i].lng,pointList[i].lat);

            path.push(Number(lnglat[0]));
            path.push(Number(lnglat[1]));
            pathArr.push(path);
        }
        paths.push(pathArr);

        startPointX = paths[0][0][0];
        startPointY = paths[0][0][1]
        endPointX = paths[0][paths[0].length-1][0];
        endPointY = paths[0][paths[0].length-1][1];

        addMarkerAndRoute();
    }

    function centerPointAndZoom(){
        let centerMaxX=this.pointList[0].lng;
        let centerMaxY=this.pointList[0].lat;
        let centerMinX=this.pointList[0].lng;
        let centerMinY=this.pointList[0].lat;

        for (let i = 0; i < this.pointList.length; i++) {
            if(Number(this.pointList[i].lng)>Number(centerMaxX)){
                centerMaxX = this.pointList[i].lng;
            }
            if(Number(this.pointList[i].lat)>Number(centerMaxY)){
                centerMaxY = this.pointList[i].lat;
            }
        }
        for (let i = 0; i < this.pointList.length; i++) {
            if(Number(this.pointList[i].lng)<Number(centerMinX)){
                centerMinX = this.pointList[i].lng;
            }
            if(Number(this.pointList[i].lat)<Number(centerMinY)){
                centerMinY = this.pointList[i].lat;
            }
        }
        
        //计算缩放比例-判断基准轴
        let zoom1;
        if((Number(centerMaxX)-Number(centerMinX))/(Number(centerMaxY)-Number(centerMinY))
            >(Number(map.extent.xmax)-Number(map.extent.xmin))/(Number(map.extent.ymax)-Number(map.extent.ymin))){
            zoom1 = (centerMaxX-centerMinX)/(map.extent.xmax-map.extent.xmin);
        }else{
            zoom1 = (centerMaxY-centerMinY)/(map.extent.ymax-map.extent.ymin);
        }
        let zoom2 = Math.log2(zoom1)
        let zoom3 = Math.floor(map.getZoom()-zoom2);
        map.setZoom(zoom3);

        //中心点位置
        let centerX = (Number(centerMaxX)+Number(centerMinX))/2;
        let centerY = (Number(centerMaxY)+Number(centerMinY))/2;

        rmark.setMapCenterAt(centerX,centerY);
    }

    //轨迹回放
    function moveReplay(){ 
        if(!isMoving){
            isMoving = true;
            map.disableDoubleClickZoom();
            map.disableScrollWheelZoom();
            map.hideZoomSlider();
            moveingStart();
        }
    }   

    function moveingStart(){
        if(count>=paths[0].length-1){
            return;
        }
        //原始位置
        let x = paths[0][count][0];
        let y = paths[0][count][1];

        //起点
        let x1 = paths[0][count][0];
        let y1 = paths[0][count][1];
       
        //终点
        let x2 = paths[0][count+1][0];
        let y2 = paths[0][count+1][1];

        //速度
        let speed = 10;

        //角度
        let slope = (y2 - y1) / (x2 - x1);
        let atan = Math.atan(slope);

        if(x2 - x1 < 0){
            atan = atan + Math.PI
        }

        moving = setInterval(() => {
            rmark.removeById('pointCarIcon');

            //每次动画运动点坐标
            x += Math.cos(atan)*speed;
            y += Math.sin(atan)*speed;

            addCarMarker(x,y);
            setCarMarkerStyle();
            setCarMovingAngle(atan,x1,x2,y1,y2);
  
            if(x2-x1<0){
                if(Number(x)<=Number(x2)){
                    clearInterval(moving);
                    count++;
                    if(count<paths[0].length-1){
                        moveingStart();
                    }else{
                        count = 0;
                        isMoving = false;
                        map.enableDoubleClickZoom();
                        map.enableScrollWheelZoom();
                        map.showZoomSlider();
                    }
                }
            }else{
                if(Number(x)>=Number(x2)){
                    clearInterval(moving);
                    count++;
                    if(count<paths[0].length-1){
                        moveingStart();
                    }else{
                        count = 0;
                        isMoving = false;
                        map.enableDoubleClickZoom();
                        map.enableScrollWheelZoom();
                        map.showZoomSlider();
                    }
                }
            }
        }, 50);
    }

    //设置车辆样式
    function setCarMarkerStyle(){
        //获取车辆控件
        let carImage;
        let imageArr = document.getElementsByTagName('image');
        
        for (let i = 0; i < imageArr.length; i++) {
            if(imageArr[i].href.baseVal==='/static/carIcon.png'){
                carImage = imageArr[i];
                break;
            }
        }
        carImage.setAttribute('id','carMarkerImage');
    }

    //设置轨迹回放车辆角度
    function setCarMovingAngle(atan,x1,x2,y1,y2){
        let car_x =$("#carMarkerImage").attr("x");
        let car_y =$("#carMarkerImage").attr("y");
        let car_atan = -atan/Math.PI*180+90;

        car_x = Number(car_x) + 15;
        car_y = Number(car_y) + 15;

        $("#carMarkerImage").attr("transform","rotate("+car_atan+","+car_x+","+car_y+")");
    }

    //经纬度转墨卡托
    function changePosXy(lng,lat){
        let lnglat = WebMercatorUtilsObj.lngLatToXY(lng,lat);

        return [lnglat[0],lnglat[1]];
    }
</script>
</html>
